<template>
  <el-card class="reset-password">
    <h2>重置密码</h2>

    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
            v-model="form.oldPassword"
            type="password"
            autocomplete="off"
            placeholder="请输入原密码"
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="form.newPassword"
            type="password"
            autocomplete="off"
            placeholder="请输入新密码（至少6位）"
        />
      </el-form-item>

      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
            v-model="form.confirmPassword"
            type="password"
            autocomplete="off"
            placeholder="请再次输入新密码"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 二次确认校验
const validateConfirm = (_rule: any, value: string, callback: any) => {
  if (value !== form.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 校验规则
const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' }
  ]
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()
    await axios.post('/api/user/reset-password', {
      oldPassword: form.oldPassword,
      newPassword: form.newPassword
    })
    ElMessage.success('密码重置成功')
    handleReset()
  } catch (err: any) {
    // 如果是校验错误，不处理
    if (err instanceof Error && !err.response) return
    // 请求失败，展示后端返回的信息
    ElMessage.error(err.response?.data?.message || '重置失败')
  }
}

// 重置表单
function handleReset() {
  formRef.value.resetFields()
}
</script>

<style scoped>
.reset-password {
  padding: 24px;
}
.reset-password h2 {
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: bold;
}
</style>
